package com.springboot.apiexample.controller;

import com.google.common.cache.Cache;
import com.springboot.apiexample.annotation.ApiIdempotent;
import com.springboot.apiexample.annotation.RateLimit;
import com.springboot.apiexample.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 提交接口 幂等操作
 *
 * @author NiJo_H
 * @version 1.0
 * */
@RestController
@Slf4j
public class FormDataController {

    @Autowired
    private Cache<String, Object> cacheApi;


    /**
     * 获取有效表单ID
     */
    @GetMapping("/formId")
    public R<String> getFormDateUid() {
        //获取id
        String formId = UUID.randomUUID().toString().replace("-", "");
        cacheApi.put(formId, formId);
        return R.ok(formId);
    }

    /**
     * 提交接口 幂等
     */
    @PostMapping("sendForm")
    @ApiIdempotent
    public R<Void> sendFormData() {
        /**
         * ....过提交验证,省略业务逻辑*/
        return R.ok();
    }

    /**
     * 本地缓存测试
     */
    @GetMapping("/addCache")
    public R<String> testCache() {
        cacheApi.put("word", "hello");
        return R.ok(cacheApi.getIfPresent("word").toString());
    }

    /**
     * 限流器
     * */
    @PostMapping("/limit")
    @RateLimit(perSecond = 5)
    public R<Void> testLimit(){
        /**
         * ....获取到令牌验证通过,省略业务逻辑*/
        return R.ok();
    }
}
